package router

import (
	"fmt"
	"gin-server/controller"
	"gin-server/middleware"
	"html/template"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

// 日期格式转换
func formatAsDate(t time.Time) string {
	year, month, day := t.Date()
	return fmt.Sprintf("%d-%d-%d", year, month, day)
}

func Router() *gin.Engine {
	fmt.Println("路由加载中...")

	// 初始化
	router := gin.Default()

	// 自定义模板方法
	router.SetFuncMap(template.FuncMap{
		"formatAsDate": formatAsDate,
	})

	// 指定模板加载目录
	router.LoadHTMLGlob("templates/**")

	// 全局json格式返回
	router.Use(middleware.Json())

	// 设置日志中间件
	router.Use(middleware.Logger())

	// 跨域处理(要在路由组之前全局使用「跨域中间件」, 否则OPTIONS会返回404)
	router.Use(middleware.Cros())

	// 登录验证中间件
	//router.Use(middleware.CheckLogin())

	// 鉴权拦截器中间件
	//router.Use(middleware.CheckAuth())

	//// 验证登录后放行路由请求
	//router.Use(middleware.CheckLogin())

	// 设置静态资源路由
	router.Static("/resource", "./public/resource")
	router.StaticFile("/favicon.ico", "./public/resource/images/favicon.ico")

	/*首页*/
	router.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{
			"title": "首页",
		})
	})

	///* 用户管理 */
	user := router.Group("/api/v1/user")
	{
		user.GET("/list", controller.User.List)
		//user.GET("/detail/:id", controller.User.Detail)
		//user.POST("/add", controller.User.Add)
		//user.PUT("/update", controller.User.Update)
		//user.DELETE("/delete/:ids", controller.User.Delete)
		//user.PUT("/status", controller.User.Status)
		//user.PUT("/resetPwd", controller.User.ResetPwd)
		//user.GET("/checkUser", controller.User.CheckUser)
	}

	///* 文章 */
	//article := router.Group("article")
	//{
	//	article.GET("/list", controller.Article.List)
	//	article.GET("/detail/:id", controller.Article.Detail)
	//	article.POST("/add", controller.Article.Add)
	//	article.PUT("/update", controller.Article.Update)
	//	article.DELETE("/delete/:ids", controller.Article.Delete)
	//	article.PUT("/isTop", controller.Article.IsTop)
	//	article.PUT("/status", controller.Article.Status)
	//}

	return router
}
